package com.kx.game.center.manager;

import com.kx.core.dawn.dbs.dao.DaoManager;
import com.kx.core.dawn.dbs.entity.*;
import com.kx.game.center.common.PlayerEnum;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.common.RedisEnum;
import com.kx.game.center.dbs.DBServices;
import com.kx.game.center.redis.RedisConstant;
import com.kx.game.center.utils.Assert;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class LoadManager {

    private static Logger logger = LoggerFactory.getLogger(LoadManager.class);

    public void overLoadingRedis(List<GameServerEntity> gameServers) {
        try {
            String redisState = GSServices.redisManager.valueGet(RedisConstant.REDIS_DATA, String.class);
            if (redisState != null && redisState.equals(RedisEnum.REDIS_START.getIndex() + ""))
                return;
            Iterator<String> iterator = DBServices.getDbSessionFactorys().keySet().iterator();
            while (iterator.hasNext()) {
                String serverId = iterator.next();
                if (serverId == DBServices.myServerId || serverId == DBServices.friendServerId)
                    continue;
                List<UserInfoEntity> userInfos = DaoManager.userDao.findAll(serverId);
                if (userInfos == null || userInfos.size() == 0)
                    continue;
                for (UserInfoEntity userInfo : userInfos) {
                    RoleInfoEntity roleInfoEntity = DaoManager.roleDao.get(serverId, userInfo.getId());
                    if (roleInfoEntity == null)
                        continue;
                    RoleExtraInfoEntity roleExtraInfoEntity = DaoManager.roleExtraDao.get(serverId, roleInfoEntity.getId());
                    if (roleExtraInfoEntity == null)
                        continue;
                    GSServices.userManager.initUser(userInfo.getId() + "", userInfo.getUserName(), userInfo.getRoleName(),
                            userInfo.getIconUrl(), roleExtraInfoEntity.getDiningRoomLv() + "",
                            PlayerEnum.LOGOUT.getIndex() + "", userInfo.getLastUpdateTime() + "",
                            serverId, userInfo.getRegion(), userInfo.getSex() + "", userInfo.getFriendCode(),
                            roleInfoEntity.getId() + "");
                    GSServices.userManager.setFriendCode(userInfo.getFriendCode(), userInfo.getUserName());
                    GSServices.newFriendManager.saveRegionUser(userInfo.getRegion(), userInfo.getUserName(), null);
                }
                logger.info("服务器serverId:{} 加载{}个用户数据完成", serverId, userInfos.size());
            }
            //重载服务器信息
            for (GameServerEntity gameServerEntity : gameServers) {
                String serverId = gameServerEntity.getServerId();
                GSServices.localManager.updateGameServerInfo(serverId,
                        gameServerEntity.getIp(), gameServerEntity.getGamePort(), gameServerEntity.getGatePort(),
                        gameServerEntity.getConnectIp(), gameServerEntity.getConnectPort(),
                        gameServerEntity.getState(), gameServerEntity.getType(),
                        gameServerEntity.getTime());
                GSServices.localManager.updateServerCreateNum(serverId + "", gameServerEntity.getCreateNum());
                GSServices.localManager.updateGSLoginCount(serverId + "", gameServerEntity.getLoginNum());
                logger.info("服务器serverId:{} ip:{} 服务器加载数据完成", serverId, gameServerEntity.getIp());
            }
            //重载网关信息
            List<GatewayEntity> gateways = DaoManager.gatewayDao.findAll();
            for (GatewayEntity gatewayEntity : gateways) {
                String gateId = gatewayEntity.getGateId();
                GSServices.localManager.updateGatewayLoad(gateId, gatewayEntity.getCount());
                GSServices.localManager.updateGatewayInfo(gateId, gatewayEntity.getIp(), gatewayEntity.getPort());
                logger.info("网关gateId:{} ip:{} 网关加载数据完成", gateId, gatewayEntity.getIp());
            }
            GSServices.redisManager.valueSet(RedisConstant.REDIS_DATA, RedisEnum.REDIS_START.getIndex() + "");
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("redisError");
        }
    }

    public void shutdownHook() {
        // 退出时挂钩
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
            }
        });
    }

    //非数据加载完成状态 不允许任何业务访问 业务调用一次 检查
    public void redisState() throws Exception {
        boolean redisState = getRedisState();
        Assert.isTrue(redisState, "The redis data is not initialized finish");
    }

    public boolean getRedisState() throws Exception {
        String redisState = GSServices.redisManager.valueGet(RedisConstant.REDIS_DATA, String.class);
        return redisState != null && redisState.equals(RedisEnum.REDIS_START.getIndex() + "");
    }
}
